<style lang="less" scoped>
  .el-dialog--center .el-dialog__body {
    padding: 40px 30px 35px 40px;
  }
  .routeStrategyTime .el-form-item__label {
    text-align: left;
  }
</style>
<template>
  <el-dialog v-el-drag-dialog
    :title="dialogTitle"
    :append-to-body='true'
    :visible.sync="AddRouteDeviceShow"
    :before-close="AddRouteDeviceClose"
    width="940px"
    top="3%"
    center>
    <div class="of">
      <el-form
        class="of"
        label-position="right"
        label-width="100px"
        :disabled="dialogType === 'view'"
        :model="dialogData" :rules="dialogDataRules"
        ref="dialogDataForm">
        <div class="of fl bbd pb26" style=" width: 870px;">
          <div class="w100 clear_fixed">
            <el-form-item label="系统名称：" label-width="70px" class="fl" prop="system_id">
              <el-select :disabled="group !== 'tenancy'" v-model="dialogData.system_id" placeholder="请选择系统名称" size="medium" style="width:180px" clearable>
                <el-option
                  v-for="item in systemsLiteList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="机构名称：" label-width="130px" class="fl" prop="institution_id">
              <el-select :disabled="institutionsLiteList.length === 0" v-model="dialogData.institution_id" placeholder="请选择机构名称" size="medium" style="width:180px" clearable>
                <el-option
                  v-for="item in institutionsLiteList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="前置机：" label-width="130px" class="fl" prop="front_node_key">
              <el-select v-model="dialogData.front_node_key" placeholder="请选择前置机" size="medium" style="width:180px" clearable>
                <el-option
                  v-for="item in frontnodesInfo"
                  :key="item.id"
                  :label="item.front_node_name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="w100 mt10 clear_fixed">
            <el-form-item label="节点描述：" label-width="70px" class="fl" prop="node_name">
              <el-input
                size="medium"
                placeholder="请输入节点描述"
                style="width:180px;"
                v-model="dialogData.node_name"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="节点地址：" label-width="130px" class="fl" prop="node_host">
              <el-input
                size="medium"
                placeholder="请输入节点地址"
                style="width:180px;"
                v-model="dialogData.node_host"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="应用标识：" label-width="130px" class="fl" prop="node_aet">
              <el-input
                size="medium"
                placeholder="请输入应用标识"
                style="width:180px;"
                v-model="dialogData.node_aet"
                clearable>
              </el-input>
            </el-form-item>
          </div>
          <div class="w100 mt10 clear_fixed">
            <el-form-item label="服务端口：" label-width="70px" class="fl" prop="node_port">
              <el-input
                size="medium"
                placeholder="请输入服务端口"
                style="width:180px;"
                v-model="dialogData.node_port"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="轮询时间：" label-width="130px" class="fl" prop="cycle_seconds">
              <el-input
                size="medium"
                placeholder="请输入轮询时间"
                style="width:180px;"
                v-model="dialogData.cycle_seconds"
                clearable
                v-int>
              </el-input>
              <span class="ml10">秒</span>
            </el-form-item>
            <el-form-item label="传输语法：" label-width="106px" class="fl" prop="transfer_syntax_uid">
              <el-select v-model="dialogData.transfer_syntax_uid" placeholder="请选择" size="medium" style="width:180px" clearable>
                <el-option
                  v-for="(item, index) in transferSyntaxList"
                  :key="index"
                  :value="item.value"
                  :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="of fl pb25 mt30 bbd" style=" width: 870px;">
          <div class="w100 clear_fixed">
            <el-form-item label="路由指定类型的影像：" label-width="140px" class="fl">
              <el-input
                size="medium"
                placeholder="请输入"
                style="width:220px;"
                v-model="dialogData.specify_modalitys"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="路由指定部位的影像：" label-width="140px" class="fr">
              <el-input
                size="medium"
                placeholder="请输入"
                style="width:220px;"
                v-model="dialogData.specify_exam_body_parts"
                clearable>
              </el-input>
            </el-form-item>
          </div>
          <div class="w100 mt10 clear_fixed">
            <el-form-item label="路由指定设备的影像：" label-width="140px" class="fl">
              <el-input
                size="medium"
                placeholder="请输入"
                style="width:220px;"
                v-model="dialogData.specify_ae_ts"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="路由指定时间的影像：" label-width="140px" class="fr">
              <el-date-picker
                v-model="dialogData.begin_study_date_time"
                align="right"
                type="date"
                placeholder="开始日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="routeScheduleTimePickerOptions"
                style="width:220px">
              </el-date-picker>
            </el-form-item>
          </div>
        </div>
        <div class="of fl pb15 mt30" style=" width: 870px;">
          <div class="w100 clear_fixed lh40">
            <div class="fl">
              <el-checkbox v-model="dialogData.is_emergency_first" :true-label="1" :false-label="0" label="优先路由急诊的影像" class="mr84"></el-checkbox>
              <el-checkbox v-model="dialogData.is_filter_thin_thickness" :true-label="1" :false-label="0" label="过滤薄层影像序列"></el-checkbox>
            </div>
            <el-form-item label="小于等于：" label-width="123px" class="fl" prop="filter_thickness">
              <el-input-number style="width: 100px" size="medium" v-model="dialogData.filter_thickness" controls-position="right" :min="0"></el-input-number>
              <span class="ml10">毫米</span>
            </el-form-item>
          </div>
          <div class="w100 mt10 clear_fixed">
            <el-form-item label="路由策略执行时间：" label-width="140px" class="fl routeStrategyTime">
              <!-- <el-time-picker
                is-range
                v-model="performTime"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                style="width: 240px">
              </el-time-picker> -->
              <el-time-picker
                v-model="dialogData.perform_begin_time"
                value-format="HH:mm:ss"
                placeholder="开始时间"
                style="width: 140px">
              </el-time-picker>
              <span> - </span>
              <el-time-picker
                v-model="dialogData.perform_end_time"
                value-format="HH:mm:ss"
                placeholder="结束时间"
                style="width: 140px">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="失败重试次数：" label-width="133px" class="fl" prop="retry_number">
              <el-input-number style="width: 100px" size="medium" v-model="dialogData.retry_number" controls-position="right" :min="1"></el-input-number>
              <span class="ml10">次</span>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer mt20 fr">
        <el-button @click="AddRouteDeviceClose" size="medium" class="mr20">关 闭</el-button>
        <el-button v-if="dialogType !== 'view'" type="primary" @click="AddRouteDeviceSave('dialogDataForm')" size="medium">保 存</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { validIP, validURL, validPort } from '@/utils/validate'
import { mapGetters } from 'vuex'

export default {
  data () {
    let requiredValidator = function (tip) {
      return (rule, value, callback) => {
        if(value === '') {
          callback(new Error(tip))
        }else {
          callback()
        }
      }
    }
    let node_nameValidator = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入节点描述'))
      }else {
        if(value.length > 40) {
          callback(new Error('节点描述长度限制：40个字符'))
        }else {
          callback()
        }
      }
    }
    let urlValidator = (rule, value, callback) => {
      if(value !== '') {
        if(validURL(value) || validIP(value)) {
          return callback()
        }else {
          return callback(new Error('节点地址格式错误'))
        }
      }else {
        return callback(new Error('请输入节点地址'))
      }
    }
    let aetValidator = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入应用标识'))
      }else {
        callback()
      }
    }
    let portValidator = (rule, value, callback) => {
      if(value !== '') {
        if(validPort(value)) {
          callback()
        }else {
          callback(new Error('端口号范围为0-65535'))
        }
      }else {
        callback(new Error('请输入端口号'))
      }
    }
    let iptNumRequiredValidator = (rule, value, callback) => {
      if(value === undefined) {
        callback(new Error('请输入'))
      }else {
        callback()
      }
    }
    let timesValidator = (rule, value, callback) => {
      if(value === undefined) {
        callback(new Error('请输入'))
      }else {
        this.dialogData.retry_number = parseInt(value)
        callback()
      }
    }
    return {
      dialogTitle: '新增路由策略',
      dialogData: {
        system_id: '',
        system_name: '',
        institution_id: '',
        institution_name: '',
        front_node_key: '',
        node_name: '',
        node_host: '',
        node_aet: '',
        node_port: '',
        cycle_seconds: '',
        retry_number: 1,
        transfer_syntax_uid: '',
        specify_modalitys: '',
        specify_ae_ts: '',
        specify_exam_body_parts: '',
        perform_begin_time: '00:00:00',
        perform_end_time: '23:59:59',
        begin_study_date_time: '',
        is_emergency_first: '',
        is_filter_thin_thickness: '',
        filter_thickness: 0
      },
      dialogDataRules: {
        system_id: [{
          trigger: 'blur',
          validator: requiredValidator('请选择客户名称')
        }],
        institution_id: [{
          trigger: 'blur',
          validator: requiredValidator('请选择机构名称')
        }],
        node_name: [{
          trigger: 'blur',
          validator: node_nameValidator
        }],
        node_host: [{
          trigger: 'blur',
          validator: urlValidator
        }],
        node_aet: [{
          validator: aetValidator
        }],
        node_port: [{
          validator: portValidator
        }],
        cycle_seconds: [{
          trigger: 'blur',
          validator: requiredValidator('请输入轮询时间')
        }],
        filter_thickness: [{
          trigger: 'blur',
          validator: iptNumRequiredValidator
        }],
        retry_number: [{
          trigger: 'blur',
          validator: timesValidator
        }]
      },
      // 传输语法
      transferSyntaxList: [
        {
          value: '1.2.840.10008.1.2',
          label: 'ImplicitVRLittleEndian'
        },
        {
          value: '1.2.840.10008.1.2.2',
          label: 'ExplicitVRBigEndian'
        },
        {
          value: '1.2.840.10008.1.2.1',
          label: 'ExplicitVRLittleEndian'
        },
        {
          value: '1.2.840.10008.1.2.1.99',
          label: 'DeflatedExplicitVRLittleEndian'
        },
        {
          value: '1.2.840.10008.1.2.4.50',
          label: 'JPEGProcess1'
        },
        {
          value: '1.2.840.10008.1.2.4.70',
          label: 'JPEGProcess14SV1'
        },
        {
          value: '1.2.840.10008.1.2.4.80',
          label: 'JPEGLSLossless'
        },
        {
          value: '1.2.840.10008.1.2.4.81',
          label: 'JPEGLSNearLossless'
        },
        {
          value: '1.2.840.10008.1.2.4.90',
          label: 'JPEG2000Lossless'
        },
        {
          value: '1.2.840.10008.1.2.4.91',
          label: 'JPEG2000Lossy'
        },
        {
          value: '1.2.840.10008.1.2.5',
          label: 'RLELossless'
        }
      ],
      routeScheduleTimePickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      performTimePickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // tenantOptions: [],
      institutionsLiteList: [], // 机构名称
      isInstitutionsClear: 1, // 打开dialog后第一次改变系统名称,不清空机构名称的值,后面每次都清空,dialogType为add时,从第一次开始就清空机构名称的值
    }
  },
  props: ['AddRouteDeviceShow', 'rowId', 'dialogType', 'frontnodesInfo', 'systemsLiteList'],
  computed: {
    ...mapGetters(['group', 'systemid']),
    performTime: {
      get () {
        if(this.dialogData.perform_begin_time === '' && this.dialogData.perform_end_time === '') {
          return null
        }else {
          return [this.dialogData.perform_begin_time, this.dialogData.perform_end_time]
        }
      },
      set (val) {
        if (val) {
          this.dialogData.perform_begin_time = val[0]
          this.dialogData.perform_end_time = val[1]
        } else {
          this.dialogData.perform_begin_time = '' // 不填写默认全天
          this.dialogData.perform_end_time = '' // 不填写默认全天
        }
      }
    }
  },
  watch: {
    dialogType (newVal) { // 修改弹窗标题
      this.dialogTitle = newVal === 'add' ? '新增路由策略' : newVal === 'view' ? '查看' : newVal === 'modify' ? '修改' : ''
      if (newVal === 'add') {
        this.resetDialogData()
        this.$emit('resetRowId')
      }
    },
    AddRouteDeviceShow(newVal) {
      this.$nextTick(() => {
        if(newVal) {
          this.$refs['dialogDataForm'].resetFields()
          if(this.group === 'dept') { // 科室角色
            this.$nextTick(() => {
              this.dialogData.system_id = this.systemid
            })
          }
          if(this.dialogType !== 'add') {
            this.getRouteStrategy(this.rowId)
          }
        }
      })
    },
    'dialogData.system_id': {
      handler: function (newVal) {
        if(newVal === '') {
          this.dialogData.system_name = ''
        }else {
          this.systemsLiteList.forEach((ele) => {
            if(ele.id === newVal) {
              this.dialogData.system_name = ele.name
            }
          })
          if(this.dialogType === 'add') {
            this.dialogData.institution_id = ''
          }
          if(this.dialogType === 'modify' && this.isInstitutionsClear === 2) {
            this.dialogData.institution_id = ''
          }
          this.getInstitutionsLiteList(newVal) // 获取机构名称
        }
      }
    },
    'dialogData.institution_id': {
      handler: function (newVal) {
        if(newVal === '') {
          this.dialogData.institution_name = ''
        }else {
          this.institutionsLiteList.forEach((ele) => {
            if(ele.id === newVal) {
              this.dialogData.institution_name = ele.name
            }
          })
        }
      }
    },
  },
  methods: {
    AddRouteDeviceClose () {
      this.$emit('AddRouteDeviceClose', '')
    },
    AddRouteDeviceSave (formName) { // 保存按钮
      this.$refs[formName].validate((valid) => {
        if(valid) {
          if (this.dialogType === 'add') {
            this.addRouteDevice()
          } else if (this.dialogType === 'modify') {
            this.updateRouteStrategy()
          }
        }else {
          return false
        }
      })
    },
    async addRouteDevice () { // 新增
      const res = await this.$pacsApi.pacsApi.addRouteDevice(this.dialogData)
      const { code, msg } = res
      if (code === 0) {
        this.$message({
          type: 'success',
          message: msg
        })
        this.AddRouteDeviceClose()
        this.$emit('refreshTable')
        // 重置数据
        this.$emit('resetRowId')
      }
    },
    async updateRouteStrategy () { // 更新
      const res = await this.$pacsApi.pacsApi.updateRouteStrategy(this.dialogData, this.rowId)
      const { code, msg } = res
      if (code === 0) {
        this.$message({
          type: 'success',
          message: msg
        })
        this.AddRouteDeviceClose()
        this.$emit('refreshTable')
        // 重置数据
        this.$emit('resetRowId')
      }
    },
    async getRouteStrategy () {
      const res = await this.$pacsApi.pacsApi.getRouteStrategy(this.rowId)
      const { code, data } = res
      if (code === 0) {
        this.dialogData = data
      }
    },
    resetDialogData () {
      this.dialogData = this.$options.data().dialogData
    },
    // async getTenantInfo() {
    //   let res = await this.$pacsApi.pacsApi.getTenantInfo()
    //   let { code, data } = res
    //   if(code === 0) {
    //     this.tenantOptions.push(data)
    //     console.log(this.dialogData.tenantId)
    //   }
    // }
    async getInstitutionsLiteList(val) {
      if(val) {
        let res = await this.$pacsApi.pacsApi.getInstitutionsLiteList({ system_id: val })
        let { code, data } = res
        if(code === 0) {
          this.institutionsLiteList = data
        }
      }
    },
  },
  mounted () {
    // this.getTenantInfo()
  }
}
</script>
